from django.db import models
# from django.contrib.auth.models import User
from django.shortcuts import reverse
from bcm_auth.models import User
from mdeditor import fields as md_models
from multiselectfield import MultiSelectField


class Category(models.Model):
    assortment = models.CharField(blank=True, max_length=10, verbose_name="分类名称")
    en_assortment = models.CharField(blank=True, max_length=10, verbose_name="分类英文")
    is_nav = models.BooleanField(default=False, verbose_name="是否在导航栏显示")

    def __str__(self):
        return self.assortment

    def to_dict(self, fields=None, exclude=None):
        data = {}
        for f in self._meta.concrete_fields + self._meta.many_to_many:
            value = f.value_from_object(self)

            if fields and f.name not in fields:
                continue

            if exclude and f.name in exclude:
                continue

            if isinstance(f, models.ManyToManyField):
                value = [i.id for i in value] if self.pk else None

            if isinstance(f, models.DateTimeField):
                value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None

            data[f.name] = value

        return data

    class Meta:
        verbose_name_plural = '文章类别'
        verbose_name = '文章类别'


class Article(models.Model):
    id = models.AutoField(primary_key=True, max_length=32)
    title = models.CharField(max_length=64, blank=False, verbose_name='标题')
    summary = models.CharField(blank=True, max_length=1024, verbose_name="摘要")
    content = md_models.MDTextField(verbose_name='正文', blank=False)
    tag = models.CharField(max_length=50, blank=True, verbose_name="标签")
    create_time = models.DateTimeField(blank=False, auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(blank=False, auto_now=True, verbose_name='更新时间')
    delete = models.BooleanField(default=False, verbose_name="文章是否删除")
    # hide为隐藏或者草稿文章
    hide = models.BooleanField(default=False, verbose_name="隐藏/草稿")
    # 是否为MD编辑的文章，目前只支持admin后台修改添加，前台允许
    md = models.BooleanField(default=False, verbose_name="MD文章")
    # 文章是否置顶
    top = models.BooleanField(default=False, verbose_name="推荐")
    author_detail = models.ForeignKey(User, on_delete=False, verbose_name='作者')
    category = models.ForeignKey(Category, default=1, on_delete=False, verbose_name="分类")

    @property
    def category_name(self):
        return self.category.assortment

    @property
    def username(self):
        return self.author_detail.username

    @property
    def nick_name(self):
        return self.author_detail.nick_name

    @property
    def last_update_time(self):
        return self.update_time.strftime('%Y-%m-%d %H:%M:%S')

    @property
    def ad(self):
        return self.author_detail.ad

    def __str__(self):
        return 'ID:%s-《%s》-作者:%s' % (self.id, self.title, self.username)

    def to_dict(self, fields=None, exclude=None):
        data = {}
        for f in self._meta.concrete_fields + self._meta.many_to_many:
            value = f.value_from_object(self)

            if fields and f.name not in fields:
                continue

            if exclude and f.name in exclude:
                continue

            if isinstance(f, models.ManyToManyField):
                value = [i.id for i in value] if self.pk else None

            if isinstance(f, models.DateTimeField):
                value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None

            data['username'] = self.username
            data['nick_name'] = self.nick_name
            data['category_name'] = self.category_name

            data[f.name] = value

        return data

    def get_absolute_url(self):
        return reverse('article-detail-view', kwargs={'article_id': self.id})
        # return '/article_detail/' + str(self.id) + ".html"

    class Meta:
        verbose_name_plural = '文章列表'
        verbose_name = '文章列表'


class Comment(models.Model):
    """
    文章评论
    """
    article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="文章")
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(max_length=1000, verbose_name="评论内容")
    com_time = models.DateTimeField(auto_now_add=True, blank=True, verbose_name="评论时间")
    farther_comment_id = models.IntegerField(blank=True, default=-1, verbose_name="上个评论编号")

    @property
    def article_title(self):
        return self.article.title

    @property
    def update_time(self):
        return self.com_time.strftime('%Y-%m-%d %H:%M:%S')

    def to_dict(self, fields=None, exclude=None):
        data = {}
        for f in self._meta.concrete_fields + self._meta.many_to_many:
            value = f.value_from_object(self)

            if fields and f.name not in fields:
                continue

            if exclude and f.name in exclude:
                continue

            if isinstance(f, models.ManyToManyField):
                value = [i.id for i in value] if self.pk else None

            if isinstance(f, models.DateTimeField):
                value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None

            data[f.name] = value

            # 子评论列表children id
            data['cid'] = []

            # 评论人
            data['people'] = self.user.username

        return data

    class Meta:
        verbose_name_plural = '评论管理'
        verbose_name = '评论管理'


class Notice(models.Model):
    """
    公告模板
    """
    text = models.TextField(max_length=1024, blank=True)

    class Meta:
        verbose_name = verbose_name_plural = '公告栏'

    def __str__(self):
        return self.text


class FriendLinks(models.Model):
    """
    友情链接
    """
    name = models.CharField(max_length=32, blank=False, verbose_name="站点名称")
    url = models.URLField(max_length=64, blank=False, verbose_name="链接")

    class Meta:
        verbose_name = verbose_name_plural = '友情链接'


class Carousel(models.Model):
    """
    首页轮播图
    """
    href = models.URLField(max_length=100, blank=True, verbose_name="图片目标地址")
    img = models.ImageField(verbose_name="图片")

    class Meta:
        verbose_name_plural = '首页轮播图'
        verbose_name = '首页轮播图'


class BBdMultiSelectField(MultiSelectField):
    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)
